import router from './router';
import { getCache,setCache } from '@/utils/session';
import getPageTitle from '@/utils/getPageTitle';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import store from './store';
import { resetRouter } from '@/router';

NProgress.configure({ showSpinner: false }); // NProgress Configuration
//判断是否已加载过动态/静态路由
var isGetRouter = false;

router.beforeEach(async (to, from, next) => {
    NProgress.start();

    document.title = getPageTitle(to.meta.title);
    const isLogin = getCache('TOKEN');
    let tenant = getCache('tenant') || 'master';

    if (to.name == 'login') {
        isGetRouter = false;
        next();
        NProgress.done();
    } else {
        if (!isLogin) {
            next(`/${tenant}/login`);
            isGetRouter = false;
        } else {
            const userInfo = store.state.user.accountInfo || '';
            if (userInfo) {
                next();
                NProgress.done();
            } else {
                try {
                    await store.dispatch('user/getUserInfo');
                    let accountRoute = store.getters.baseRoute;
                    let menu = accountRoute;
                    var menuRouter = filterAsyncRouter(menu)
                    let allmenuRouter = flatAsyncRoutes(menuRouter)
                    allmenuRouter.forEach(item => {
                        if(item.meta?.isExternal=='true'){
                            router.addRoute(item)
                        }else{
                            router.addRoute("layout", item)
                        }
                    })
                    next({ ...to, replace: true });
                    NProgress.done();
                } catch (err) {
                    next(`/${tenant}/login`);
                    NProgress.done();
                }
            }
        }
    }
});


router.afterEach(() => {
    NProgress.done();
});

//转换
function filterAsyncRouter(routerMap) {
    const accessedRouters = []
    routerMap.forEach(item => {
        item.meta = item.meta ? item.meta : {};
        item.meta.isExternal = item.isExternal;
        //MAP转路由对象
        var route = {
            path: item.path,
            name: item.name,
            meta: item.meta,
            hidden: item.extendone == 'true' ? true : false,
            redirect: item.redirect,
            children: item.children ? filterAsyncRouter(item.children) : null,
            component: loadComponent(item.path)
        }
        accessedRouters.push(route)
    })
    return accessedRouters
}
function loadComponent(component) {
    if(component){
        return (resolve) => require([`@/views${component}`],resolve)
    }

}

//路由扁平化
function flatAsyncRoutes(routes, breadcrumb = []) {
    let res = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (tmp.children) {
            let childrenBreadcrumb = [...breadcrumb]
            childrenBreadcrumb.push(route)
            let tmpRoute = { ...route }
            tmpRoute.meta.breadcrumb = childrenBreadcrumb
            delete tmpRoute.children
            res.push(tmpRoute)
            let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb)
            childrenRoutes.map(item => {
                res.push(item)
            })
        } else {
            let tmpBreadcrumb = [...breadcrumb]
            tmpBreadcrumb.push(tmp)
            tmp.meta.breadcrumb = tmpBreadcrumb
            res.push(tmp)
        }
    })
    return res
}
